package com.palm.platform.controller;

import com.palm.core.anno.Auth;
import com.palm.core.util.Captcha;
import com.palm.core.util.StringUtil;
import com.palm.platform.Config;
import com.palm.platform.Current;
import com.palm.platform.domain.User;
import com.palm.platform.domain.UserInfo;
import com.palm.platform.service.CacheDataService;
import com.palm.platform.service.UserService;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.MethodType;
import org.noear.solon.core.handle.Result;
import org.noear.solon.extend.sqltoy.annotation.Db;
import org.sagacity.sqltoy.SqlToyContext;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;


import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@Auth
@Controller
@Mapping("system")
public class SystemController {

    @Inject
    SqlToyContext sqlToyContext;
    @Db
    SqlToyLazyDao dao;
    @Inject
    UserService userService;
    @Inject
    CacheDataService cacheDataServce;

    @Inject("${app.title:Easy Admin}")
    String appName;
    @Inject("${app.logo:img/logo.png}")
    String logo;

    @Init
    public void init() {
        //sqlToyContext.getTranslateManager().put();
    }

//    @Auth(login=false)
//    @Note("获取机构")
//    @Mapping("branch")
//    public Result<List> branch(String parent){
//    	return Result.succeed(cacheDataServce.getBaranchs(parent));
//    }
//    @Auth(login=false)
//    @Note("获取地区")
//    @Mapping("district")
//    public Result<List> district(String parent){
//    	return Result.succeed(cacheDataServce.getDistrict(parent));
//    }

    @Auth(login=false)
    @Note("从translate中获取字典")
    @Mapping("translate/{cache}")
    public Result<Map> translate(String cache, String type) {
//        if(type==null){
//            return Result.succeed(new HashMap());
//        }
        HashMap<String, Object[]> cacheData = sqlToyContext.getTranslateManager().getCacheData(cache, type);
        Map result = new HashMap();
        if (cacheData != null) {
            result = cacheData.entrySet().stream()
                    .collect(Collectors.toMap(
                            key -> key.getKey(),
                            value -> value.getValue()[1]));
        }
        return Result.succeed(result);
    }
    @Auth(login = false)
    @Note("从translate中获取字典")
    @Mapping("dict")
    public Result<Map> allDict(String type){
        return Result.succeed(cacheDataServce.allCodes());
    }

    @Auth(login = false)
    @Note("保持在线")
    @Mapping("keep")
    public Result keepOnline() {
        UserInfo user=Current.user(Current.USER);
        if(user!=null){
            return Result.succeed(user.getUsername());
        }
        return Result.succeed();
    }
    @Auth(login = false)
    @Mapping("login")
    public Result login(String username, String password, String verify) {
        Context ctx = Context.current();
        if (!Captcha.verify(verify, ctx)) {
            return Result.failure("验证码错误");
        }
        if (StringUtil.isEmpty(password)) {
            return Result.failure("用户名或密码错误");
        }
        UserInfo userInfo = userService.loadUserInfo(username, password);
        if (userInfo != null) {
            //ctx.sessionSet(Current.userSessionId, userInfo);
            Current.login(userInfo);
            return Result.succeed();
        } else {
            return Result.failure("用户名或密码错误");
        }
    }


    @Auth(login = false)
    @Mapping(value = "app_info", method = MethodType.GET)
    public Result appInfo() {
        Map<String, Object> info = new HashMap<>();
        info.put("appName", appName);
        info.put("logo", logo);
        return Result.succeed(info);
    }
    @Mapping(value = "configs", method = MethodType.GET)
    public Result configs() {
        return Result.succeed(Config.configMap());
    }

    @Mapping(value = "updateConfig", method = MethodType.POST)
    public Result updateConfig(String code, String value){
//        com.palm.platform.domain.Config config = new com.palm.platform.domain.Config();
//        config.setCode(code);
//        config.setValue(value);
//        Long flg = dao.update(config);
//        if(flg > 0){
//            return Result.succeed();
//        }
        Config.saveConfig(code,value);
        return Result.succeed();
    }

    @Mapping(value = "user_info", method = MethodType.GET)
    public Result<UserInfo> userInfo(Context ctx) {
        UserInfo userInfo=Current.user();
      //  Current.setLoginToken(ctx,userInfo);
        return Result.succeed(userInfo);
    }
    @Mapping("logout")
    public Result logout(Context ctx){
//        ctx.sessionClear();
//        ctx.cookieSet("_t"+Current.USER,null);

        Current.logout();
        return Result.succeed();
    }
    //http://localhost:9095/system/changePassword
    @Mapping("changePassword")
    public Result changePassword(String OldPassword,String ConfirmPassword,String Password){
       if(!Objects.equals(ConfirmPassword,Password)){
           return Result.failure("两次密码不一致");
       }
       if(StringUtil.isEmpty(Password)){
           return Result.failure("密码不能为空");
       }
        UserInfo userInfo= Current.user();
       if(!Objects.equals(userInfo.getPassword(),StringUtil.md5Hex(userInfo.getUsername()+"$"+OldPassword))){
           return Result.failure("原密码不正确");
       }
        User u=new User();
       u.setId(Long.valueOf(userInfo.getId()));
       u.setPassword(StringUtil.md5Hex(userInfo.getUsername()+"$"+Password));
       dao.update(u);
       userInfo.setPassword(u.getPassword());
       return Result.succeed("密码已修改");
    }
}
